package cn.tedu.user.service.impl;

import cn.tedu.common.ex.ScServiceException;
import cn.tedu.common.util.JWTUtil;
import cn.tedu.common.util.JwtConstants;
import cn.tedu.common.vo.ResponseCode;
import cn.tedu.user.domain.dto.ClientLoginParam;
import cn.tedu.user.domain.dto.ClientSaveParam;
import cn.tedu.user.domain.dto.Clientupdateparam;
import cn.tedu.user.domain.po.Client;
import cn.tedu.user.mapper.ClientMapper;
import cn.tedu.user.service.ClientService;
import cn.tedu.user.util.PasswordEncoderUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class ClientServiceImpl implements ClientService {
    @Autowired
    private ClientMapper clientMapper;

    @Autowired
    private RedisTemplate redisTemplate;
    //用户登录实现
    @Override
    public String login(ClientLoginParam clientLoginParam) {
        log.debug("准备处理用户登录业务:ClientLoginParam={}", clientLoginParam);
        // 判断用户名是否正确
        Client client = clientMapper.selectByname(clientLoginParam.getName());
        // 如果用户名不存在，抛出异常/
        if(client==null){
            throw new ScServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"用户名不存在");
        }
        // 如果用户名存在，判断密码是否正确
        if(!PasswordEncoderUtil.decrypt(clientLoginParam.getPassword(),client.getPasswordHash())){
            throw new ScServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"密码不正确");
        }
        // 准备token数据
        // 生成token
        Map<String,Object> map = new HashMap<>();
        map.put("name",client.getName());
        map.put("clientId",client.getClientId());
        String token = JWTUtil.getToken(map);
        // redis存储 key规则 sso:userId  token
        redisTemplate.opsForValue().set(JwtConstants.SSO + client.getClientId(),token,3L, TimeUnit.MINUTES);
        return token;
    }

    public static void main(String[] args) throws Exception, IOException {

        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod("http://sms.webchinese.cn/web_api/");
        post.addRequestHeader("Content-Type",
                "application/x-www-form-urlencoded;charset=gbk");//在头文件中设置转码
        NameValuePair[] data = { new NameValuePair("Uid", "Kiven"),//注册的用户名
                new NameValuePair("Key", "d41d8cd98f00b204e980"),//注册成功后,登录网站使用的密钥
                new NameValuePair("smsMob", "13420019471"),//手机号码
                new NameValuePair("smsText", "【中山吉祥购公司】验证码：8888")};//设置短信内容
        post.setRequestBody(data);
        client.executeMethod(post);
        Header[] headers = post.getResponseHeaders();
        int statusCode=post.getStatusCode();
        System.out.println("statusCode:"+statusCode);
        for (Header header : headers) {
            System.out.println(header.toString());
        }
        String result = new String(post.getResponseBodyAsString().getBytes("gbk"));
        System.out.println(result);
        post.releaseConnection();
    }
    @Override
    public void saveClient(ClientSaveParam clientSaveParam) {
        log.debug("准备处理用户注册业务:ClientSaveParam={}", clientSaveParam);
        // 判断用户名是否已存在
        if(clientMapper.selectByname(clientSaveParam.getName())!=null){
            throw new ScServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"用户名已存在");
        }
        //判断邮箱是否已存在
        if(clientMapper.selectByemail(clientSaveParam.getEmail())!=null){
            throw new ScServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"邮箱已存在");
        }
        Client client = new Client();
        BeanUtils.copyProperties(clientSaveParam,client);

        client.setPasswordHash(PasswordEncoderUtil.enc(clientSaveParam.getPassword()));
        client.setRegistrationDate(new Date());
        client.setVerificationStatus("0");
        clientMapper.insert(client);

    }
    @Override
    public void updateClient(Clientupdateparam clientupdateparam) {
        log.debug("修改用户业务:client={}",clientupdateparam);
        //判断用户名是否正确
        if(clientMapper.selectByname(clientupdateparam.getName())==null){
            throw new ScServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"用户名不存在");
        }
        //判断手机号是否正确
        if(clientMapper.selectByphoneNumber(clientupdateparam.getPhoneNumber())==null){
            throw new ScServiceException(ResponseCode.INTERNAL_SERVER_ERROR,"手机号错误");
        }
        clientupdateparam.setPassword(PasswordEncoderUtil.enc(clientupdateparam.getPassword()));
        clientMapper.updateClient(clientupdateparam);


    }
    @Override
    public void deleteClient(Long clientId) {
        log.debug("删除用户业务:clientId={}",clientId);
        clientMapper.deleteById(clientId);
    }


}
